package com.cloudcreativity.blyg.ui.goods;

import android.app.Activity;
import android.content.Context;
import android.databinding.ObservableField;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.cloudcreativity.blyg.R;
import com.cloudcreativity.blyg.base.BaseBindingRecyclerViewAdapter;
import com.cloudcreativity.blyg.base.BaseDialogImpl;
import com.cloudcreativity.blyg.base.BaseModel;
import com.cloudcreativity.blyg.databinding.ActivityGoodsListBinding;
import com.cloudcreativity.blyg.databinding.ItemLayoutGoodsBinding;
import com.cloudcreativity.blyg.sqlite.CategoryOne;
import com.cloudcreativity.blyg.sqlite.CategoryTwo;
import com.cloudcreativity.blyg.sqlite.Goods;
import com.cloudcreativity.blyg.sqlite.utils.CategoryDaoUtils;
import com.cloudcreativity.blyg.sqlite.utils.GoodsDaoUtils;
import com.cloudcreativity.blyg.utils.APIService;
import com.cloudcreativity.blyg.utils.AddGoodsUtils;
import com.cloudcreativity.blyg.utils.AlertDialogUtils;
import com.cloudcreativity.blyg.utils.CheckDialog;
import com.cloudcreativity.blyg.utils.EditGoodsUtils;
import com.cloudcreativity.blyg.utils.LogUtils;
import com.cloudcreativity.blyg.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GoodsListModel extends BaseModel<Activity, ActivityGoodsListBinding> {

    public BaseBindingRecyclerViewAdapter<Goods, ItemLayoutGoodsBinding> adapter;

    private MyCategoryAdapter categoryAdapter;

    public ObservableField<String> key = new ObservableField<>();

    private long cateOneId;
    private long cateTwoId;

    private int pageNum = 1;
    private static final int size = 20;
    private GoodsDaoUtils goodsDaoUtils;

    private boolean loading = false;

    GoodsListModel(final Activity context, final ActivityGoodsListBinding binding, BaseDialogImpl baseDialog) {
        super(context, binding, baseDialog);
        goodsDaoUtils = new GoodsDaoUtils(context);

        adapter = new BaseBindingRecyclerViewAdapter<Goods, ItemLayoutGoodsBinding>(context) {
            @Override
            protected int getLayoutResId(int viewType) {
                return R.layout.item_layout_goods;
            }

            @Override
            protected void onBindItem(ItemLayoutGoodsBinding binding, final Goods item, int position) {
                binding.setItem(item);
                binding.tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlertDialogUtils utils = new AlertDialogUtils(context,"提示",
                                "确定删除吗？");
                        utils.setOnResultListener(new AlertDialogUtils.OnResultListener() {
                            @Override
                            public void onOk() {
                                goodsDaoUtils.delete(item.getLid());
                                pageNum = 1;
                                loadData(pageNum,cateOneId,cateTwoId,key.get());
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        utils.show();
                    }
                });

                binding.tvCheck.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 盘库
                        CheckDialog checkDialog = new CheckDialog(context);
                        checkDialog.setOnOkLisntener(new CheckDialog.OnOkListener() {
                            @Override
                            public void onOk(boolean isAdd, double stock) {
                                if(isAdd){
                                    item.setStock(item.getStock()+stock);
                                }else{
                                    item.setStock(item.getStock()-stock);
                                }
                                goodsDaoUtils.update(item);
                                pageNum = 1;
                                loadData(pageNum,cateOneId,cateTwoId,key.get());
                            }
                        });
                        checkDialog.show();
                    }
                });

                binding.tvModify.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 修改信息
                        EditGoodsUtils editGoodsUtils = new EditGoodsUtils(context, item);
                        editGoodsUtils.setOnOkListener(new EditGoodsUtils.OnOkListener() {
                            @Override
                            public void onOk(Goods goods) {
                                goodsDaoUtils.update(goods);
                                pageNum = 1;
                                loadData(pageNum,cateOneId,cateTwoId,key.get());
                            }
                        });
                        editGoodsUtils.show();
                    }
                });
            }
        };

        binding.rcvGoods.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false));

        //加上分割线
        DividerItemDecoration itemDecoration = new DividerItemDecoration(context,DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(context.getResources().getDrawable(R.drawable.shape_item_divide));
        binding.rcvGoods.addItemDecoration(itemDecoration);

        //加载分类数据
        new Thread(){
            @Override
            public void run() {
                final List<CategoryOne> categories = new CategoryDaoUtils(context).getAllCategories();
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        categoryAdapter = new MyCategoryAdapter(context,categories);
                        binding.elvCategory.setAdapter(categoryAdapter);
                        // binding.elvCategory.expandGroup(0);
                        cateOneId = categories.get(0).getId();
                        cateTwoId = categories.get(0).getSeconds().get(0).getId();
                        binding.elvCategory.expandGroup(0,true);
                        //默认加载数据
                        loadData(pageNum,cateOneId,cateTwoId,key.get());
                    }
                });
            }
        }.start();

        binding.elvCategory.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                CategoryTwo two = (CategoryTwo) categoryAdapter.getChild(i,i1);
                cateOneId = two.getCategoryOneId();
                cateTwoId = two.getId();
                pageNum = 1;
                key.set("");
                loadData(pageNum,cateOneId,cateTwoId,key.get());
                return true;
            }
        });

        binding.rcvGoods.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(!loading && !recyclerView.canScrollVertically(1)){
                    loadData(pageNum,cateOneId,cateTwoId,key.get());
                }

            }
        });
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    private void loadData(final int page,long cateOne,long cateTwo,final String key){
        if(loading) return;
        loading = true;
        new Thread(){
            @Override
            public void run() {
                final List<Goods> goods = goodsDaoUtils.queryByPage(page, size,cateOneId,cateTwoId, null==key?"":key);
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loading = false;
                        if(goods==null||goods.isEmpty()){
                            //没有数据
                            if(page==1){
                                adapter.getItems().clear();
                            }
                        }else{
                            //有数据
                            if(page==1){
                                adapter.getItems().clear();
                            }
                            pageNum ++;
                            adapter.getItems().addAll(goods);
                        }
                    }
                });
            }
        }.start();
    }

    public void onBack(){
        context.finish();
    }

    public void onAddClick(){
        AddGoodsUtils addGoodsUtils = new AddGoodsUtils(context,"",getBaseDialog());
        addGoodsUtils.setOnOkListener(new AddGoodsUtils.OnOkListener() {
            @Override
            public void onOk(final Goods goods) {
                goodsDaoUtils.insert(goods);
                pageNum = 1;
                loadData(pageNum,cateOneId,cateTwoId,key.get());
                //将商品数据保存到远程服务器
                OkHttpClient client = new OkHttpClient();
                FormBody body = new FormBody.Builder()
                        .addEncoded("barCode",goods.getBarCode())
                        .addEncoded("brandName", TextUtils.isEmpty(goods.getBrandName())?"":goods.getBrandName())
                        .addEncoded("categoryOneId",String.valueOf(goods.getCategoryOneId()))
                        .addEncoded("categoryTwoId",String.valueOf(goods.getCategoryTwoId()))
                        .addEncoded("name",goods.getName())
                        .addEncoded("price",String.valueOf(goods.getPrice()))
                        .addEncoded("specName",TextUtils.isEmpty(goods.getSpecName())?"":goods.getSpecName())
                        .addEncoded("unit",TextUtils.isEmpty(goods.getUnit())?"":goods.getUnit())
                        .build();
                Request request = new Request.Builder().url(APIService.HOST_APP+"/base/addBaseGoods")
                        .post(body)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        LogUtils.e("xuxiwu",result);
                        try {
                            JSONObject object = new JSONObject(result);
                            if(object.getInt("status")==1){
                                //添加成功，将返回的信息保存
                                JSONObject info = object.getJSONObject("info");
                                long goodsId = info.getLong("goodsId");
                                int brandId = info.getInt("brandId");
                                goods.setId(goodsId);
                                goods.setBrandId(brandId);
                                goodsDaoUtils.update(goods);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


            }
        });
        addGoodsUtils.show();
    }

    void onScan(final String code){
                Goods goods = goodsDaoUtils.queryByCode(code);
                if(goods==null){
                    AlertDialogUtils utils = new AlertDialogUtils(context,"提示",
                            "没有该商品，是否要添加？");
                    utils.setOnResultListener(new AlertDialogUtils.OnResultListener() {
                        @Override
                        public void onOk() {
                            AddGoodsUtils addGoodsUtils = new AddGoodsUtils(context,code,getBaseDialog());
                            addGoodsUtils.setOnOkListener(new AddGoodsUtils.OnOkListener() {
                                @Override
                                public void onOk(final Goods goods) {
                                    boolean result = goodsDaoUtils.insert(goods);
                                    if(!result){
                                        ToastUtils.showShortToast(context,"该商品已存在");
                                        return;
                                    }
                                    pageNum = 1;
                                    loadData(pageNum,cateOneId,cateTwoId,key.get());

                                    //将商品数据保存到远程服务器
                                    OkHttpClient client = new OkHttpClient();
                                    FormBody body = new FormBody.Builder()
                                            .addEncoded("barCode",goods.getBarCode())
                                            .addEncoded("brandName", TextUtils.isEmpty(goods.getBrandName())?"":goods.getBrandName())
                                            .addEncoded("categoryOneId",String.valueOf(goods.getCategoryOneId()))
                                            .addEncoded("categoryTwoId",String.valueOf(goods.getCategoryTwoId()))
                                            .addEncoded("name",goods.getName())
                                            .addEncoded("price",String.valueOf(goods.getPrice()))
                                            .addEncoded("specName",TextUtils.isEmpty(goods.getSpecName())?"":goods.getSpecName())
                                            .addEncoded("unit",TextUtils.isEmpty(goods.getUnit())?"":goods.getUnit())
                                            .build();
                                    Request request = new Request.Builder()
                                            .url(APIService.HOST_APP+"/base/addBaseGoods")
                                            .post(body)
                                            .build();
                                    Call call = client.newCall(request);
                                    call.enqueue(new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {

                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            String result = response.body().string();
                                            LogUtils.e("xuxiwu",result);
                                            try {
                                                JSONObject object = new JSONObject(result);
                                                if(object.getInt("status")==1){
                                                    //添加成功，将返回的信息保存
                                                    JSONObject info = object.getJSONObject("info");
                                                    long goodsId = info.getLong("goodsId");
                                                    int brandId = info.getInt("brandId");
                                                    goods.setId(goodsId);
                                                    goods.setBrandId(brandId);
                                                    goodsDaoUtils.update(goods);
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            });
                            addGoodsUtils.show();
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    utils.show();
                }else{
                    adapter.getItems().clear();
                    adapter.getItems().add(goods);
                }
    }

    public static class MyCategoryAdapter extends BaseExpandableListAdapter{

        private Context context;
        private List<CategoryOne> categoryOnes;

        MyCategoryAdapter(Context context,List<CategoryOne> categoryOnes) {
            this.context = context;
            this.categoryOnes = categoryOnes;
        }

        @Override
        public int getGroupCount() {
            return categoryOnes.size();
        }

        @Override
        public int getChildrenCount(int i) {
            return categoryOnes.get(i).getSeconds().size();
        }

        @Override
        public Object getGroup(int i) {
            return categoryOnes.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return categoryOnes.get(i).getSeconds().get(i1);
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return categoryOnes.get(i).getSeconds().get(i1).getId();
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
            final CategoryHolder categoryHolder;
            if(view==null){
                view = LayoutInflater.from(context)
                        .inflate(R.layout.item_layout_category_one,viewGroup,false);
                categoryHolder = new CategoryHolder();
                categoryHolder.tvTitle = view.findViewById(R.id.tv_title);
                view.setTag(categoryHolder);
            }else{
                categoryHolder = (CategoryHolder) view.getTag();
            }
            categoryHolder.tvTitle.setText(categoryOnes.get(i).getName());
            return view;
        }

        @Override
        public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
            final CategoryHolder categoryHolder;
            if(view==null){
                view = LayoutInflater.from(context)
                        .inflate(R.layout.item_layout_category_two,viewGroup,false);
                categoryHolder = new CategoryHolder();
                categoryHolder.tvTitle = view.findViewById(R.id.tv_title);
                view.setTag(categoryHolder);
            }else{
                categoryHolder = (CategoryHolder) view.getTag();
            }
            categoryHolder.tvTitle.setText(categoryOnes.get(i).getSeconds().get(i1).getName());
            return view;
        }

        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }

        static class CategoryHolder{
            TextView tvTitle;
        }

    }

}
